package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {

	var counter Counter
	//启用10个协程-进行读取
	for i := 0; i < 10; i++ {
		go func() {
			for {
				counter.Read()
				time.Sleep(time.Millisecond)
			}
		}()
	}

	//主协程就是写数据
	for {
		counter.Write()
		time.Sleep(time.Second)
	}

}

type Counter struct {
	count uint64
	mu    sync.RWMutex
}

func (c *Counter) Write() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.count++
	fmt.Println("write:", c.count)
}

func (c *Counter) Read() uint64 {
	c.mu.RLock()
	defer c.mu.RUnlock()
	fmt.Println("read:", c.count)
	return c.count
}
